<template>
  <div class="blog-comment-container">
    <MessageArea
        :list="data.rows" title="评论列表"
        :subTitle="`(${data.total})`"
        :isListLoading="isLoading"
        @submit="handleSubmit"
    ></MessageArea>
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import {getComments, postComment} from "@/api/blog";
import fetchdata from "@/mixins/fetchdata";

export default {
  name: "BlogComment",
  mixins: [fetchdata({total: 0, rows: []})],
  components: {
    MessageArea
  },
  data() {
    return {
      page: 1,
      limit: 10
    }
  },
  computed: {
    hasMore() {
      return this.data.rows.length < this.data.total;
    },
  },
  methods: {
    async fetchData() {
      return await getComments(this.$route.params.id, this.page, this.limit)
    },
    async handleSubmit(formData, callback) {
      const resp = await postComment({
        blogId: this.$route.params.id,
        ...formData,
      });
      this.data.rows.unshift(resp);
      this.data.total++;
      callback("评论成功"); // 告诉子组件，我这边处理完了，你继续
    },

    async fetchMore() {
      if(!this.hasMore) {
        return;
      }
      this.isLoading = true;
      this.page ++;
      let data = await this.fetchData();
      this.data.total = data.total;
      this.data.rows = this.data.rows.concat(data.rows);
      this.isLoading = false;
    },

    handleScroll(dom) {
      if(this.isLoading || !dom) {
        return;
      }
      let range = 100;
      let dec = Math.abs( dom.scrollTop + dom.clientHeight - dom.scrollHeight );
      if(dec <= range) {
        this.fetchMore();
      }
    }
  },
  created() {
    this.$eventBus.$on("mainScroll", this.handleScroll)
  },
  destroyed() {
    this.$eventBus.$off("mainScroll", this.handleScroll);
  }
}
</script>

<style scoped lang="less">
.blog-comment-container {
  margin: 30px 0;
  border-top: 1px solid #008c8c;
  padding-top: 20px;
}
</style>
